//
//  HomeViewController.m
//  CheXunWang
//
//  Created by zhu lin on 12/8/11.
//  Copyright 2011 Zhulin. All rights reserved.
//

#import "HomeViewController.h"
#import "CheXunWangAppDelegate.h"
#import "HttpServices.h"
#import "SeriesViewController.h"
#import "BrandsViewController.h"
#import "PriceSelectorViewController.h"

@interface HomeViewController()
@property (nonatomic, retain) ASIHTTPRequest *newsRequest;

- (void)getNews;
@end

@implementation HomeViewController
@synthesize hud;
@synthesize newsRequest;

+ (HomeViewController *)sharedViewController
{
	static HomeViewController *sHomeViewController;
	if (sHomeViewController == nil) {
		@synchronized(self) {
			sHomeViewController = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
			assert(sHomeViewController != nil);
		}
	}
	return sHomeViewController;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	self.hud = [[ATMHud alloc] init];
	[self.view addSubview:self.hud.view];
	
	//[self getNews];
}

- (void)viewWillAppear:(BOOL)animated
{
	[self.hud hide];
	[self.newsRequest clearDelegatesAndCancel];
}

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
	self.hud = nil;
	self.newsRequest = nil;
}

- (void)dealloc {
	[newsRequest release];
	[hud release];
    [super dealloc];
}

#pragma mark -
#pragma mark touch events
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	[searchTF resignFirstResponder];
}

#pragma mark -
#pragma mark getNews
- (void)getNews
{
	self.newsRequest = [HttpServices getLatestNewsWithDelegate:self];
}

/*
 [
 {"id":152829,"link":"http://www.chexun.com/news/20111207/152829.html",
 "seriesId":null,"modelId":null,"title":"如何让轮胎长寿 车讯网汽车讲堂系列37",
 "catagoryName":"星爷",
 "firstImage":"http://photo.chexun.com/images/newsinfo/2011-12/7/default/201112711932841803855.jpg"},
 {"id":152554,"link":"http://www.chexun.com/news/20111206/152554.html",
 "seriesId":null,"modelId":null,"title":"刹车片何时更换 车讯网汽车讲堂系列36",
 "catagoryName":"星爷",
 "firstImage":"http://photo.chexun.com/images/newsinfo/2011-12/5/default/2011125171213641536971.jpg"}
 ]
 
 */
- (void)requestFinished:(ASIHTTPRequest *)request
{
	/*
	NSArray *imageRequestArray = [self.imageDownloadsInProgress allKeysForObject:request];
	if (imageRequestArray == nil || [imageRequestArray count] == 0) {	
		// brandslist request
		NSData *responseData = [request responseData];
		NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
		
		NSArray *ungroupedArray = (NSArray *)[result JSONValue];
		if (!ungroupedArray || [ungroupedArray count] == 0) {
			self.groupedBrandArray = [NSMutableArray array];
		} else {
			self.groupedBrandArray = [HttpServices groupArray:ungroupedArray byKey:kSectionKey];
		}
		
		[self.hud hide];
		[self.tableView reloadData];
	} else {
		// loadimage request
		NSIndexPath *indexPath = [imageRequestArray objectAtIndex:0];
		UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
		UIImageView *imageView = (UIImageView *)[cell.contentView viewWithTag:kImageTag];
		imageView.image = [self loadImageOfIndexPath:indexPath];
		[[imageView layer] setCornerRadius:5.0f];
		[self.imageDownloadsInProgress removeObjectForKey:indexPath];
	}
	 */
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
	/*
	NSArray *imageRequestArray = [self.imageDownloadsInProgress allKeysForObject:request];
	if (imageRequestArray == nil || [imageRequestArray count] == 0) {
		[self.hud setAccessoryPosition:ATMHudAccessoryPositionLeft];
		[self.hud setCaption:@"访问出错！"];
		[self.hud setImage:[UIImage imageNamed:@"11-x"]];
		[self.hud setActivity:NO];
		[self.hud update];
		[self.hud hideAfter:1.0f];
	} else {
		// stop loadimage
		NSIndexPath *indexPath = [imageRequestArray objectAtIndex:0];
		[self.imageDownloadsInProgress removeObjectForKey:indexPath];
	}
	 */
}


#pragma mark -
#pragma mark actions
- (IBAction)searchButtonPressed:(id)sender
{
	NSString *searchText = [searchTF.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
	
	if (searchText && ![searchText isEqualToString:@""]) {
		SeriesViewController *seriesVC = [[SeriesViewController alloc] initWithNibName:@"SeriesViewController" bundle:nil];
		seriesVC.title = searchText;
		seriesVC.backType = ZLBackButtonTypeHome;
		
		//
		[self dismissModalViewControllerAnimated:YES];
		[CheXunWangAppDelegate shareAppDelegate].tabbarController.selectedIndex = 0;
		UINavigationController *currentNav = [[CheXunWangAppDelegate shareAppDelegate].tabbarController.viewControllers objectAtIndex:0];
		[currentNav popToRootViewControllerAnimated:NO];
		[currentNav pushViewController:seriesVC animated:NO];
		
		[seriesVC getSeriesBySeriesName:searchText];
		[seriesVC release];
		return;
	}
	
	//提示输入不能为空
	[self.hud setCaption:@"输入不能为空！"];
	[self.hud show];
	[self.hud hideAfter:1.0];
}

- (IBAction)showCalculator
{
	
}

- (IBAction)showCarLib
{
	[self dismissModalViewControllerAnimated:YES];
	[CheXunWangAppDelegate shareAppDelegate].tabbarController.selectedIndex = 0;
	UINavigationController *currentNav = [[CheXunWangAppDelegate shareAppDelegate].tabbarController.viewControllers objectAtIndex:0];
	
	UIViewController * topViewController = currentNav.topViewController;
	if ([topViewController isKindOfClass:[BrandsViewController class]]) {
		BrandsViewController * cvc = (BrandsViewController *)topViewController;
		[cvc getAllBrands];
	} else {
		[currentNav popToRootViewControllerAnimated:NO];
		BrandsViewController * cac = [[BrandsViewController alloc] initWithNibName:@"BrandsViewController" bundle:nil];
		[currentNav pushViewController:cac animated:NO];
		[cac getAllBrands];
		[cac release];
	}
}

- (IBAction)showPriceSelector
{
	[self dismissModalViewControllerAnimated:YES];
	
	[CheXunWangAppDelegate shareAppDelegate].tabbarController.selectedIndex = 1;
	UINavigationController *currentNav = (UINavigationController *)[CheXunWangAppDelegate shareAppDelegate].tabbarController.selectedViewController;
	
	UIViewController * topViewController = currentNav.topViewController;
	if (![topViewController isKindOfClass:[PriceSelectorViewController class]])
	{
		[currentNav popToRootViewControllerAnimated:NO];
		PriceSelectorViewController * pVC = [[PriceSelectorViewController alloc] initWithNibName:@"PriceSelectorViewController" bundle:nil];
		[currentNav pushViewController:pVC animated:NO];
		[pVC release];
	}
}

- (IBAction)showAssistant
{
	
}

- (IBAction)showCarComparator
{
	
}

- (IBAction)show4SHelper
{
	
}

#pragma mark -
#pragma mark textfeild delegate methods
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
	return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
	[textField resignFirstResponder];
	[self searchButtonPressed:nil];
	return YES;
}
@end
